package com.fjb.service.order.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjb.common.entity.HttpCode;
import com.fjb.common.entity.JsonPagesResult;
import com.fjb.common.entity.JsonResult;
import com.fjb.common.entity.PageQuery;
import com.fjb.common.enums.DataSource;
import com.fjb.common.enums.order.OrderStatus;
import com.fjb.common.utils.SerialNumberUtils;
import com.fjb.dto.AddOrderCart;
import com.fjb.dto.LoginUserInfo;
import com.fjb.mapper.cart.ShoppingCartMapper;
import com.fjb.mapper.order.OrderInfoMapper;
import com.fjb.mapper.order.OrderProductMapper;
import com.fjb.mapper.order.OrderStatusLogMapper;
import com.fjb.pojo.cart.ShoppingCart;
import com.fjb.pojo.order.OrderInfo;
import com.fjb.pojo.order.OrderProduct;
import com.fjb.pojo.order.OrderStatusLog;
import com.fjb.pojo.order.query.OrderInfoQuery;
import com.fjb.pojo.order.vo.OrderInfoPageVo;
import com.fjb.pojo.user.SysUserAddress;
import com.fjb.service.order.OrderInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * <p>
 * 订单信息 服务实现类
 * </p>
 *
 * @author hemiao
 * @since 2020-02-08
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
	
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Autowired
	private OrderStatusLogMapper orderStatusLogMapper;
	@Autowired
	private ShoppingCartMapper shoppingCartMapper;
	
	@Transactional
	@Override
	public JsonResult<Integer> addOreder(LoginUserInfo userInfo, List<AddOrderCart> addOrderCartList,
			SysUserAddress address) {
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		Integer userId = userInfo.getUserId();
		Integer mainUserId = userInfo.getMainUserId();
		
		List<Integer> inCartList = new ArrayList<Integer>();
		for (AddOrderCart addOrderCart : addOrderCartList) {
			Integer cartId = addOrderCart.getId();
			inCartList.add(cartId);
		}
		QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<ShoppingCart>();
		queryWrapper.in("id", inCartList);
		queryWrapper.eq("user_id", userId);
		List<ShoppingCart> cartList = shoppingCartMapper.selectList(queryWrapper);
		if(cartList.size()==0) {
			httpCode.setMsg("购物车已清空");
			return new JsonResult<Integer>(null, httpCode);
		}
		String consigneeName = address.getConsigneeName();
		String consigneePhone = address.getConsigneePhone();
		String province = address.getProvince();
		String city = address.getCity();
		String county = address.getCounty();
		String address2 = address.getAddress();
		
		// 订单金额
		BigDecimal orderPrice = new BigDecimal(0);
		// 优惠金额
		BigDecimal discountAmount = new BigDecimal(0);
		// 运费
		BigDecimal freightAmount = new BigDecimal(0);
		// 支付金额	
		BigDecimal payAmount = new BigDecimal(0);
		// 购买数量 
		Integer orderSkuCount = 0;
		// 卖家id
		Integer sellerUserId = null;
		// 图片
		StringJoiner sj = new StringJoiner(",");
		
		for (ShoppingCart sc : cartList) {
			Integer skuCount = sc.getSkuCount();
			BigDecimal skuPrice = sc.getSkuPrice();
			String skuFileUrl = sc.getSkuFileUrl();
			orderSkuCount = orderSkuCount + skuCount;	
			orderPrice = orderPrice.add(skuPrice.multiply(new BigDecimal(skuCount)));
			if(StringUtils.isNotBlank(skuFileUrl)) {				
				sj.add(skuFileUrl);
			}	
			sellerUserId = sc.getSellerUserId();
		}	
		String skuFileUrls = sj.toString();
		OrderStatus orderStatus = OrderStatus.STATUS_4;
		DataSource dataSource = DataSource.WX_APPLET;
		LocalDateTime createTime = LocalDateTime.now();
		// 订单编号 
		String orderNumber = SerialNumberUtils.createNumber(SerialNumberUtils.ORDER_INFO, userId);
		OrderInfo oi = new OrderInfo();
		oi.setMainUserId(mainUserId);
		oi.setUserId(userId);
		oi.setOrderNumber(orderNumber);
		oi.setSellerUserId(sellerUserId);
		oi.setConsigneeName(consigneeName);
		oi.setConsigneePhone(consigneePhone);
		oi.setProvince(province);
		oi.setCity(city);
		oi.setCounty(county);
		oi.setAddress(address2);
		oi.setOrderPrice(orderPrice);
		oi.setDiscountAmount(discountAmount);
		oi.setFreightAmount(freightAmount);
		oi.setSkuCount(orderSkuCount);
		oi.setPayAmount(payAmount);
		oi.setOrderStatus(orderStatus.getCode());
		oi.setCreateTime(createTime);
		oi.setCreateUserId(userId);
		oi.setDataSource(dataSource.getCode());
		oi.setSkuFileUrls(skuFileUrls);
		
		// 添加订单
		orderInfoMapper.insert(oi);
		Integer orderId = oi.getId();
		
		// 添加订单产品记录
		List<OrderProduct> orderProductList = new ArrayList<OrderProduct>();
		for (ShoppingCart sc : cartList) {
			Integer cartId = sc.getId();
			Integer productId = sc.getProductId();
			Integer skuCount = sc.getSkuCount();
			Integer attrSkuId = sc.getAttrSkuId();
			BigDecimal skuPrice = sc.getSkuPrice();
			String attrSkuJson = sc.getAttrSkuJson();
			String skuFileUrl = sc.getSkuFileUrl();
			for (AddOrderCart aoc : addOrderCartList) {
				Integer id = aoc.getId();
				if(id.equals(cartId)) {
					String remark2 = aoc.getRemark();
					if(StringUtils.isNotBlank(remark2)) {
						// 提交订单的时候 每个产品都可以 添加备注
						sc.setRemark(remark2);
					}
				}
			}	
			String remark = sc.getRemark();
			Integer sellerUserId2 = sc.getSellerUserId();
			String productName = sc.getProductName();
			String productUnit = sc.getProductUnit();
			String cartDataSource = sc.getDataSource();
			Integer categoryId = sc.getCategoryId();
			Integer brandId = sc.getBrandId();
			
			OrderProduct op = new OrderProduct();
			op.setSellerUserId(sellerUserId2);
			op.setMainUserId(mainUserId);
			op.setUserId(userId);
			op.setOrderId(orderId);
			op.setProductId(productId);
			op.setAttrSkuId(attrSkuId);
			op.setSkuPrice(skuPrice);
			op.setSkuCount(skuCount);
			op.setSkuFileUrl(skuFileUrl);
			op.setAttrSkuJson(attrSkuJson);
			op.setCreateTime(createTime);
			op.setCreateUserId(userId);
			op.setRemark(remark);	
			// 购物车冲那里添加的
			op.setDataSource(cartDataSource);
			op.setProductName(productName);
			op.setProductUnit(productUnit);
			op.setCategoryId(categoryId);
			op.setBrandId(brandId);
			orderProductList.add(op);
		}	
		orderProductMapper.addBatch(orderProductList);
		
		// 添加订单状态日志
		OrderStatusLog osl = new OrderStatusLog();
		osl.setMainUserId(mainUserId);
		osl.setUserId(userId);
		osl.setOrderId(orderId);
		osl.setOrderStatus(orderStatus.getCode());
		osl.setStatusMsg(orderStatus.getMsg());
		osl.setCreateTime(createTime);
		osl.setCreateUserId(userId);
		orderStatusLogMapper.insert(osl);
		
		// 购物车清空
		shoppingCartMapper.delete(queryWrapper);
		
		// 生成订单	 减少产品库存
		
		
		return new JsonResult<Integer>(orderId, HttpCode.SUCCESS);
	}
		
	@Override
	public JsonPagesResult<List<OrderInfoPageVo>> selectPageList(PageQuery pageQuery, OrderInfoQuery orderQuery) {
		PageHelper.startPage(pageQuery.getCurrentPage(), pageQuery.getPageSize());
		List<OrderInfoPageVo> infoList = orderInfoMapper.selectPageList(orderQuery);
		PageInfo<OrderInfoPageVo> pageInfo = new PageInfo<OrderInfoPageVo>(infoList);
		if(infoList.size()>0) {		
			List<Integer> inOrderId = new ArrayList<Integer>();
			for (OrderInfoPageVo il : infoList) {
				inOrderId.add(il.getId());
			}
			QueryWrapper<OrderProduct> queryWrapper = new QueryWrapper<OrderProduct>();
			queryWrapper.in("order_id", inOrderId);
			List<OrderProduct> productList = orderProductMapper.selectList(queryWrapper);
			for (OrderInfoPageVo il : infoList) {
				Integer orderId = il.getId();
				List<OrderProduct> opList = new ArrayList<OrderProduct>();
				for (OrderProduct op : productList) {
					if(op.getOrderId().equals(orderId)) {
						opList.add(op);
					}
				}
				il.setProductList(opList);
				Integer orderStatus = il.getOrderStatus();
				String orderStatusMsg = OrderStatus.getOrderStatusMsg(orderStatus);
				il.setOrderStatusMsg(orderStatusMsg);
			}
		}
		return new JsonPagesResult<List<OrderInfoPageVo>>(infoList, HttpCode.SUCCESS, pageInfo.getTotal(), pageInfo.getPages());
	}

}
